package com.ccnu.demojava.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class RTestReflect {
	
	public class RField{
		public String name;
		public String value;
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getValue() {
			return value;
		}
		public void setValue(String value) {
			this.value = value;
		}
	}
	
	private Object getFieldValueByName(Object o, String fieldName) {
		String getter = "get" + fieldName;
		Method method = null;
		for (Method m:o.getClass().getMethods()) {
			if(m.getName().toLowerCase().equals(getter.toLowerCase())) {
				if(m.getParameterCount() == 0) {
					method = m;
					break;
				}
			}
		}
		if(method != null) {
			try {
				Object value = method.invoke(o, new Object[] {});
				return value;
			} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return null;
	}
	
	public List getFieldsInfo(Object o) {
		ArrayList<Field> fieldLists = new ArrayList<>();
		for (Field f : o.getClass().getDeclaredFields()) {
			Object v = getFieldValueByName(o, f.getName());
			System.out.println(f.getName() + ":" + f.getType() + ":" + ( (v==null)?"null":v.toString()) );
			fieldLists.add(f);
		}		
		return fieldLists;		
	}
}
